package com.example.quickstartconsumer.controller;

import com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery;
import com.alibaba.nacos.api.exception.NacosException;
import com.example.quickstartconsumer.client.UserClient;
import com.example.quickstartconsumer.dto.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private NacosServiceDiscovery serviceDiscovery;

    @Autowired
    private UserClient userClient;

    @GetMapping(value = "/nacos/consumer/{str}")
    public String getService(@PathVariable("str") String str) throws
            NacosException {
        //从Nacos中获取服务地址
        ServiceInstance serviceInstance =
                serviceDiscovery.getInstances("quickstart-provider").get(0);
        String url = serviceInstance.getHost() + ":" +
                serviceInstance.getPort();
        return restTemplate.getForObject("http://" + url + "/nacos/service/"+
                str, String.class);
    }

    @GetMapping(value = "/user/list")
    public List<User> getUserList() {
        return userClient.getAllUser();
    }
}
